import { API_SIDEBAR_PATH, SPEC_CACHE_PATH } from "./constants";
import * as fs from "fs";

const loadAllowedTags = (): string[] => {
  if (fs.existsSync(SPEC_CACHE_PATH)) {
    try {
      const spec = JSON.parse(fs.readFileSync(SPEC_CACHE_PATH, "utf8"));
      return spec.tags?.map((tag: any) => tag.name) || [];
    } catch (e) {
      console.warn("Could not load OpenAPI spec for tag filtering:", e);
    }
  }
  return [];
};

export const loadSonarApiSidebar = (): any[] => {
  const allowedTags = loadAllowedTags();

  if (fs.existsSync(API_SIDEBAR_PATH)) {
    try {
      const sidebarModule = require(API_SIDEBAR_PATH);
      // The sidebar.ts exports the array directly via: export default sidebar.apisidebar;
      let apiSidebarItems = sidebarModule.default || sidebarModule || [];

      // Filter to only show tags that are defined in the spec
      apiSidebarItems = apiSidebarItems.filter((item: any) => {
        if (item.type !== "category") {
          return true;
        }

        return allowedTags.includes(item.label);
      });

      console.log(`Filtered API sidebar to ${apiSidebarItems.length} items`);
      return apiSidebarItems;
    } catch (e) {
      console.warn("Could not load pre-generated API sidebar:", e);
      return [];
    }
  }
  return [];
};

// Helper function to find and replace the "api-reference" category
export const replaceApiReferenceCategory = (
  items: any[],
  sonarApiItems: any[],
): any[] => {
  return items.map((item) => {
    if (
      item.type === "category" &&
      item.label === "api-reference" &&
      item.items !== undefined
    ) {
      // Replace the api-reference category items with the filtered autogenerated API sidebar
      return {
        ...item,
        label: "Sonar API Reference",
        items: sonarApiItems,
      };
    }

    if (item.items) {
      return {
        ...item,
        items: replaceApiReferenceCategory(item.items, sonarApiItems),
      };
    }

    return item;
  });
};
